package com.itjin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itjin.mapper.*;
import com.itjin.model.domain.entity.*;
import com.itjin.model.domain.vo.*;
import com.itjin.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

  @Resource
  private PostMapper postMapper;
  @Resource
  private UserMapper userMapper;
  @Resource
  private SearchHistoryMapper searchHistoryMapper;
  @Resource
  private SearchKeywordMapper searchKeywordMapper;

  @Override
  @Transactional
  public SearchResultVO search(String keyword, Integer userId) {
    // 1. 记录搜索历史
    SearchHistory history = new SearchHistory();
    history.setUserId(userId);
    history.setKeyword(keyword);
    history.setSearchType(3); // 综合搜索
    history.setCreateTime(new Date());

    // 2. 更新热门搜索
    SearchKeyword searchKeyword = searchKeywordMapper.selectById(keyword);
    if (searchKeyword == null) {
      searchKeyword = new SearchKeyword();
      searchKeyword.setKeyword(keyword);
      searchKeyword.setSearchCount(1);
      searchKeyword.setHotScore(1);
      searchKeyword.setFirstSearchTime(new Date());
      searchKeyword.setLastSearchTime(new Date());
      searchKeywordMapper.insert(searchKeyword);
    } else {
      searchKeyword.setSearchCount(searchKeyword.getSearchCount() + 1);
      searchKeyword.setHotScore(searchKeyword.getHotScore() + 1);
      searchKeyword.setLastSearchTime(new Date());
      searchKeywordMapper.updateById(searchKeyword);
    }

    // 3. 搜索帖子
    QueryWrapper<Post> postWrapper = new QueryWrapper<>();
    postWrapper.like("title", keyword)
        .or()
        .like("content", keyword)
        .eq("postStatus", 3)
        .orderByDesc("createTime");
    List<Post> posts = postMapper.selectList(postWrapper);

    // 4. 搜索用户
    QueryWrapper<User> userWrapper = new QueryWrapper<>();
    userWrapper.like("username", keyword)
        .or()
        .like("userAccount", keyword)
        .eq("userStatus", 0)
        .eq("isDelete", 0);
    List<User> users = userMapper.selectList(userWrapper);

    // 5. 转换为VO
    List<GetPostListVO> postVOs = convertToPostVOs(posts);
    List<UserVO> userVOs = convertToUserVOs(users);

    // 6. 更新搜索历史的结果数
    history.setResultCount(postVOs.size() + userVOs.size());
    searchHistoryMapper.insert(history);

    return SearchResultVO.builder()
        .posts(postVOs)
        .users(userVOs)
        .total(postVOs.size() + userVOs.size())
        .build();
  }

  @Override
  public List<HotSearchVO> getHotSearches() {
    // 构建查询条件
    QueryWrapper<SearchKeyword> wrapper = new QueryWrapper<>();
    wrapper.orderByDesc("searchCount") // 首先按搜索次数降序
        .orderByAsc("firstSearchTime") // 次数相同时按首次搜索时间升序
        .last("LIMIT 10"); // 限制返回前10条

    // 查询并转换为VO
    return searchKeywordMapper.selectList(wrapper)
        .stream()
        .map(keyword -> HotSearchVO.builder()
            .keyword(keyword.getKeyword())
            .searchCount(keyword.getSearchCount())
            .hotScore(keyword.getHotScore())
            .build())
        .collect(Collectors.toList());
  }

  @Override
  public List<String> getUserSearchHistory(Integer userId) {
    QueryWrapper<SearchHistory> wrapper = new QueryWrapper<>();
    wrapper.eq("userId", userId)
        .eq("isDeleted", 0)
        .orderByDesc("createTime");

    // 获取所有搜索历史
    List<SearchHistory> historyList = searchHistoryMapper.selectList(wrapper);

    // 使用LinkedHashMap保存关键词，确保按照时间顺序处理
    Map<String, SearchHistory> keywordMap = new LinkedHashMap<>();

    // 遍历历史记录，只保留每个关键词最新的一条记录
    for (SearchHistory history : historyList) {
      String keyword = history.getKeyword();
      // 如果Map中不存在该关键词或当前记录比Map中已有记录更新，则更新Map
      if (!keywordMap.containsKey(keyword) ||
          history.getCreateTime().after(keywordMap.get(keyword).getCreateTime())) {
        keywordMap.put(keyword, history);
      }
    }

    // 转换为List并限制最多10条记录
    return keywordMap.values().stream()
        .map(SearchHistory::getKeyword)
        .limit(10)
        .collect(Collectors.toList());
  }

  @Override
  public boolean clearUserSearchHistory(Integer userId) {
    QueryWrapper<SearchHistory> wrapper = new QueryWrapper<>();
    wrapper.eq("userId", userId);

    SearchHistory update = new SearchHistory();
    update.setIsDeleted(1);

    return searchHistoryMapper.update(update, wrapper) > 0;
  }

  // 转换帖子列表为VO
  private List<GetPostListVO> convertToPostVOs(List<Post> posts) {
    if (posts == null || posts.isEmpty()) {
      return new ArrayList<>();
    }

    // 1. 获取所有作者ID
    Set<Integer> authorIds = posts.stream()
        .map(Post::getAuthorId)
        .collect(Collectors.toSet());

    // 2. 批量查询作者信息
    Map<Integer, User> userMap = userMapper.selectBatchIds(authorIds).stream()
        .collect(Collectors.toMap(User::getId, user -> user));

    // 3. 转换为VO
    return posts.stream().map(post -> {
      User author = userMap.get(post.getAuthorId());
      String authorName = author != null ? author.getUsername() : "未知用户";
      String authorAvatar = author != null ? author.getAvatar() : "";

      return GetPostListVO.builder()
          .id(post.getId())
          .authorId(post.getAuthorId())
          .authorName(post.getIsAnonymous() == 1 ? "匿名用户" : authorName)
          .authorAvatar(post.getIsAnonymous() == 1 ? "" : authorAvatar)
          .title(post.getTitle())
          .content(post.getContent())
          .image1(post.getImage1())
          .image2(post.getImage2())
          .image3(post.getImage3())
          .image4(post.getImage4())
          .image5(post.getImage5())
          .image6(post.getImage6())
          .image7(post.getImage7())
          .image8(post.getImage8())
          .image9(post.getImage9())
          .type(post.getType())
          .isAnonymous(post.getIsAnonymous())
          .createTime(post.getCreateTime())
          .updateTime(post.getUpdateTime())
          .viewsCount(post.getViewsCount())
          .commentsCount(post.getCommentsCount())
          .likesCount(post.getLikesCount())
          .collectsCount(post.getCollectsCount())
          .build();
    }).collect(Collectors.toList());
  }

  // 转换用户列表为VO
  private List<UserVO> convertToUserVOs(List<User> users) {
    if (users == null || users.isEmpty()) {
      return new ArrayList<>();
    }

    return users.stream().map(user -> UserVO.builder()
        .id(user.getId())
        .username(user.getUsername())
        .userAccount(user.getUserAccount())
        .avatar(user.getAvatar())
        .gender(user.getGender())
        .phone(user.getPhone())
        .email(user.getEmail())
        .userStatus(user.getUserStatus())
        .createTime(user.getCreateTime())
        .updateTime(user.getUpdateTime())
        .userRole(user.getUserRole())
        .biography(user.getBiography())
        .build()).collect(Collectors.toList());
  }
}
